package gameEntities;

import java.util.Random;

import javax.microedition.lcdui.game.Sprite;

import constants.Constants;

import math.Vector2D;

/**
 * The Class Fish which provides informations for all fishes.
 */
public abstract class Fish extends MovingGameEntity {
	
	private final float LEFT_FISH_BORDER = -30.0f;
	private final float RIGHT_FISH_BORDER = 1000.0f;
	
	private final boolean right;
	private final float speed;
	
	//private int bite = -1;		//for the bite animation
	private boolean flash = false;
	
	private int flashAnimCounter = 0;
	private int fishAnimationSpeedCounter = 0;
	
	
	/**
	 * Instantiates a new fish.
	 *
	 * @param sprite the sprite
	 * @param position the position
	 * @param right if right or left
	 * @param speed the fish speed
	 */
	public Fish(Sprite sprite, Vector2D position, boolean right, float speed) {
		super(sprite, position);
		
		this.right = right;
		
		if (right)
			sprite.setTransform(Sprite.TRANS_MIRROR);
		
		this.speed = speed/*1.f*/ + randSpeed();
	}
	
	/* (non-Javadoc)
	 * @see gameEntities.MovingGameEntity#Update(float)
	 */
	public void Update(float deltaTime) {
		super.Update(deltaTime);
		
		if (right)
			velocity.x = speed;
		else
			velocity.x = -speed;
		
		// check if too far outside
		if (position.x < LEFT_FISH_BORDER)
			destroyable = true;
		else if (position.x > RIGHT_FISH_BORDER)
			destroyable = true;
		
		
		// update sprite
		if(fishAnimationSpeedCounter++ > Constants.FISHANIMATIONSPEED) {	//Seegras animation
			sprite.nextFrame();
			if(this.flash) {
				if(flashAnimCounter > 6)
					this.destroyable = true;
				else
					flashAnimCounter++;
			}
			
			fishAnimationSpeedCounter = 0;
		}
	}
	
	/**
	 * Gets the time bonus that the player gets for this specific fish.
	 *
	 * @return the time bonus
	 */
	public abstract float GetTimeBonus();
	
	/**
	 * Erzeugt eine bessere Zufallsfunktion, als die existierende.
	 *
	 * @return eine Zufallszahl zwischen 0 und 1
	 */
	private float randSpeed() {
		Random r = new Random();
		r.setSeed((long)position.x);
		
		float randSpeed = 0; 
		for(int i = 0; i < 5; i++) {
			randSpeed += (((float)(Math.abs(r.nextInt()) % 1000)) / 100.f);
			r = new Random();
		}
		randSpeed = randSpeed % 10;
		randSpeed /= 5;
		
		return randSpeed;
	}
	
	/**
	 * Launches bite animation.
	 */
	/*public void bite() {
		this.bite++;
	}*/
	
	/**
	 * Launches the flash animation which kills the fish
	 */
	public void flashAndKill() {
		if(!this.flash) {
			this.flash = true;
			this.sprite.setFrameSequence(new int[] {0, 1, 0, 2, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4});
		}
	}
	
	/**
	 * Returns weather the fish has already been flashed.
	 *
	 * @return if the fish has already been flashed
	 */
	public boolean isFlashed() {
		return this.flash;
	}
}
